package utils

import (
	"grpc-server/global"
	"net"
	"strconv"
	"strings"
	"sync"
)

var portDoOne sync.Once
var ipDoOne sync.Once
var Port int
var Ip string

// GetFreePort 动态获取当前可用端口
func GetFreePort() int {
	// 本地调试用
	if global.DEV {
		return 50051
	}

	portDoOne.Do(func() {
		addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
		if err != nil {
			panic(err)
		}

		listen, err := net.ListenTCP("tcp", addr)
		if err != nil {
			panic(err)
		}

		defer listen.Close()

		Port = listen.Addr().(*net.TCPAddr).Port
	})

	return Port
}

// GetLocalIp 获取本地ip
func GetLocalIp() string {

	ipDoOne.Do(func() {
		addrs, err := net.InterfaceAddrs()
		if err != nil {
			panic(err)
		}

		for _, address := range addrs {
			// 检查ip地址判断是否回环地址
			if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
				if ipnet.IP.To4() != nil {
					// 非 169 开头的ip才可用
					ip := ipnet.IP.String()
					if judgeIp := strings.Index(ip, "169."); judgeIp == -1 {
						Ip = ip
						break
					}
					//fmt.Println(ipnet.IP.String())
				}
			}
		}
	})

	return Ip
}

// GetIpPort 获取 ip 及 port
func GetIpPort() string {
	return GetLocalIp() + ":" + strconv.Itoa(GetFreePort())
}
